package com.bree.erp.service.stateless;

import java.util.Collection;
import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.InventoryFlow;
import com.bree.erp.entity.InventoryStatus;
import com.bree.erp.entity.PartUnit;
import com.bree.erp.entity.PurchaseOrder;
import com.bree.erp.entity.User;
import com.bree.erp.entity.Warehouse;
import com.bree.erp.service.InventoryFlowService;

@Stateless
public class InventoryFlowServiceBean implements InventoryFlowService {

	@PersistenceContext()
	private EntityManager em;
	
	public InventoryFlowServiceBean() {
		
	}
	
	public InventoryFlowServiceBean(EntityManager em) {
		this.em = em;
	}
	
	@Override
	public InventoryFlow read(Long id) {
		return em.find(InventoryFlow.class, id);
	}

	@Override
	public Collection<InventoryFlow> list() {
		
		TypedQuery<InventoryFlow> query = em.createNamedQuery(InventoryFlow.QUERY_SELECT_ALL_INVENTORYFLOW, InventoryFlow.class);
		return query.getResultList();
	}

	@Override
	public InventoryFlow create(Long poId, String warehouseId, String locationBin,
			Long partUnitId, double quantity, InventoryStatus status,
			String userId) {
		
		InventoryFlow inventoryFlow = new InventoryFlow();
		PurchaseOrder po = em.find(PurchaseOrder.class,  poId);
		Warehouse warehouse = em.find(Warehouse.class, warehouseId);
		PartUnit partUnit = em.find(PartUnit.class, partUnitId);
		User user = em.find(User.class, userId);
		
		inventoryFlow.setPurchaseOrder(po);
		inventoryFlow.setLocationBin(locationBin);
		inventoryFlow.setLoggedBy(user);
		inventoryFlow.setLoggedDate(new Date());
		inventoryFlow.setPartUnit(partUnit);
		inventoryFlow.setQuantity(quantity);
		inventoryFlow.setStatus(status);
		inventoryFlow.setWarehouse(warehouse);
		
		em.persist(inventoryFlow);
		
		return inventoryFlow;
	}

}
